import {Body, Controller, Get, HttpStatus, Post, Query, Res} from '@nestjs/common';
import {Response} from 'express';
import {UserService} from '../../service/user.service';
import {CommonRedisService} from '../../service/common.redis.service';
import {CommonResponseDto} from '../../dto/common.response.dto';
import {ResCode, UserStatus} from '../../common/constants';
import AppConfig from 'config/app.config';
import {getLogStr} from "../../common/utils";
import {Logger} from '../../utils/log4js';
import {CommonRequestService} from "../../service/common.request.service";

const exception = (e) => {
  console.log(e);
  try {
    Logger.error(getLogStr(e))
  } catch(e){}
  return new CommonResponseDto(ResCode.ERROR, '服务异常', null);
}
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService, private readonly commonRedisService: CommonRedisService, private readonly commonRequestService: CommonRequestService) {}

  @Post('/login')
  async login(@Body() params: { username: string, password: string, flag: number }, @Res({ passthrough: true }) res: Response) {
    console.log(params)
    res.status(HttpStatus.OK);
    params.username = params.username || '';
    params.password = params.password || '';
    params.flag = params.flag || null;
    const { username, password, flag } = params;
    if (username && password && flag) {
      try {
        let errorCount = await this.commonRedisService.get(`${AppConfig.ErrorCountPrefix}${username}`)
        if (errorCount) {
          errorCount = Number(errorCount)
        }
        if (AppConfig.AdminUserName !== username && errorCount && errorCount >= AppConfig.MaxPwdErrorCount) {
          return new CommonResponseDto(ResCode.FORBIDDEN, '用户已被锁定');
        } else {
          const res = await this.commonRequestService.post(`${AppConfig.ServerDomain}/manage/${AppConfig.ApiPrefix}/login`, params)
          if (res.message === 'invalid username') {
            return new CommonResponseDto(res.code, '用户不存在', null)
          } else if (res.message === 'invalid password') {
            if (!errorCount) {
              errorCount = 0
            }
            await this.commonRedisService.set(`${AppConfig.ErrorCountPrefix}${username}`, errorCount+1, AppConfig.PwdErrorTimeout)
            return new CommonResponseDto(res.code, '用户名或密码错误', null)
          } else {
            if (res.code && res.data) {
              await this.commonRedisService.del(`${AppConfig.ErrorCountPrefix}${username}`)
            }
            return new CommonResponseDto(res.code, res.message, res.data)
          }
        }
      } catch(e) {
        console.log(e)
        return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
      }
    }
    return new CommonResponseDto(ResCode.ERROR, '用户名或密码不能为空', null);
  }

  @Post('/unlock')
  async unlock(@Body() params: { username: string, admin: string }, @Res({ passthrough: true }) res: Response) {
    console.log(params)
    res.status(HttpStatus.OK);
    params.username = params.username || '';
    params.admin = params.admin || '';
    const { username, admin } = params;
    if (username && admin) {
      if (admin !== AppConfig.AdminUserName) {
        return new CommonResponseDto(ResCode.ERROR, '无权限操作', null)
      }
      try {
        await this.commonRedisService.del(`${AppConfig.ErrorCountPrefix}${username}`)
        return new CommonResponseDto(ResCode.OK, '用户解锁成功', null)
      } catch(e) {
        return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
      }
    }
    return new CommonResponseDto(ResCode.ERROR, '参数不能为空', null);
  }
}
